#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
迭代器模式 (Iterator Pattern) - Python实现详解

概述引导：
迭代器模式提供一种方法顺序访问一个聚合对象中各个元素，而又不暴露该对象的内部表示。
这种类型的设计模式属于行为型模式。

学习要点：
1. Python内置迭代器协议
2. 自定义迭代器实现
3. 生成器函数
4. 生成器表达式
5. 异步迭代器

Java对比要点：
- Java使用Iterator接口和Iterable接口
- Python使用__iter__和__next__魔法方法
- Python的生成器提供更简洁的实现
- Python支持异步迭代器

关键理解：
Python的迭代器协议是语言的核心特性，生成器使迭代器实现更加简洁。
"""

from abc import ABC, abstractmethod
from typing import Any, Iterator, Iterable, List, Dict, Optional, Union, Tuple, TypeVar, Generic
from dataclasses import dataclass, field
from collections.abc import Iterator as ABCIterator, Iterable as ABCIterable
import time
import random
import asyncio
import json
from pathlib import Path
import threading
from concurrent.futures import ThreadPoolExecutor
import weakref
from enum import Enum, auto
import heapq
from datetime import datetime, timedelta
import re


# ============= Python内置迭代器协议 =============

class BasicIterator:
    """
    基础迭代器示例 - 演示Python迭代器协议
    
    Python迭代器协议要求:
    1. __iter__方法：返回迭代器对象本身
    2. __next__方法：返回下一个元素，没有元素时抛出StopIteration
    
    Java对比：
    - Java使用Iterator接口的hasNext()和next()方法
    - Python使用异常机制来标识迭代结束
    """
    
    def __init__(self, data: List[Any]):
        self.data = data
        self.index = 0
    
    def __iter__(self):
        """返回迭代器对象本身"""
        return self
    
    def __next__(self):
        """返回下一个元素"""
        if self.index >= len(self.data):
            raise StopIteration
        
        value = self.data[self.index]
        self.index += 1
        return value
    
    def reset(self):
        """重置迭代器"""
        self.index = 0


class ReverseIterator:
    """
    反向迭代器 - 从后向前遍历
    
    演示自定义迭代顺序的实现
    """
    
    def __init__(self, data: List[Any]):
        self.data = data
        self.index = len(data)
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.index <= 0:
            raise StopIteration
        
        self.index -= 1
        return self.data[self.index]


class StepIterator:
    """
    步长迭代器 - 按指定步长遍历
    
    演示带参数的迭代器实现
    """
    
    def __init__(self, data: List[Any], step: int = 1):
        self.data = data
        self.step = step
        self.index = 0
    
    def __iter__(self):
        return self
    
    def __next__(self):
        if self.index >= len(self.data):
            raise StopIteration
        
        value = self.data[self.index]
        self.index += self.step
        return value


# ============= 可迭代对象实现 =============

class IterableContainer:
    """
    可迭代容器 - 演示Iterable协议
    
    实现__iter__方法使对象可迭代
    每次调用iter()都返回新的迭代器实例
    """
    
    def __init__(self, data: List[Any]):
        self.data = data
    
    def __iter__(self):
        """返回新的迭代器实例"""
        return BasicIterator(self.data.copy())
    
    def __len__(self):
        return len(self.data)
    
    def __getitem__(self, index):
        return self.data[index]
    
    def add(self, item: Any):
        """添加元素"""
        self.data.append(item)
    
    def remove(self, item: Any):
        """移除元素"""
        if item in self.data:
            self.data.remove(item)
    
    def reverse_iter(self):
        """返回反向迭代器"""
        return ReverseIterator(self.data.copy())
    
    def step_iter(self, step: int = 2):
        """返回步长迭代器"""
        return StepIterator(self.data.copy(), step)


# ============= 生成器函数实现 =============

def simple_generator(data: List[Any]):
    """
    简单生成器函数 - Python特色实现
    
    使用yield关键字创建生成器
    
    Python优势：
    - 语法简洁，无需实现__iter__和__next__
    - 自动处理StopIteration异常
    - 惰性求值，节省内存
    """
    print("生成器开始执行")
    for i, item in enumerate(data):
        print(f"生成第{i+1}个元素: {item}")
        yield item
    print("生成器执行完毕")


def fibonacci_generator(n: int):
    """
    斐波那契数列生成器
    
    演示无限序列的生成
    """
    a, b = 0, 1
    count = 0
    
    while count < n:
        yield a
        a, b = b, a + b
        count += 1


def infinite_counter(start: int = 0, step: int = 1):
    """
    无限计数器生成器
    
    演示无限序列的实现
    """
    current = start
    while True:
        yield current
        current += step


def filtered_generator(data: Iterable[Any], predicate):
    """
    过滤生成器
    
    根据条件过滤元素
    """
    for item in data:
        if predicate(item):
            yield item


def mapped_generator(data: Iterable[Any], transform):
    """
    映射生成器
    
    对每个元素应用转换函数
    """
    for item in data:
        yield transform(item)


def batched_generator(data: Iterable[Any], batch_size: int):
    """
    批处理生成器
    
    将数据分批返回
    """
    batch = []
    for item in data:
        batch.append(item)
        if len(batch) >= batch_size:
            yield batch
            batch = []
    
    # 返回最后一批（如果有剩余）
    if batch:
        yield batch


def windowed_generator(data: Iterable[Any], window_size: int):
    """
    滑动窗口生成器
    
    返回固定大小的滑动窗口
    """
    window = []
    for item in data:
        window.append(item)
        if len(window) > window_size:
            window.pop(0)
        if len(window) == window_size:
            yield tuple(window)


# ============= 高级迭代器实现 =============

T = TypeVar('T')

class LazyIterator(Generic[T]):
    """
    惰性迭代器 - 延迟计算
    
    只在需要时才计算值，节省内存和计算资源
    """
    
    def __init__(self, data_source, transform_func=None):
        self.data_source = data_source
        self.transform_func = transform_func or (lambda x: x)
        self.cache = {}
        self.computed_indices = set()
    
    def __iter__(self):
        self.index = 0
        return self
    
    def __next__(self):
        try:
            # 尝试获取下一个元素
            if hasattr(self.data_source, '__getitem__'):
                # 支持索引访问的数据源
                if self.index >= len(self.data_source):
                    raise StopIteration
                
                # 检查缓存
                if self.index not in self.cache:
                    raw_value = self.data_source[self.index]
                    self.cache[self.index] = self.transform_func(raw_value)
                    print(f"计算索引 {self.index} 的值: {self.cache[self.index]}")
                
                value = self.cache[self.index]
                self.index += 1
                return value
            else:
                # 迭代器数据源
                raw_value = next(self.data_source)
                return self.transform_func(raw_value)
        
        except (IndexError, StopIteration):
            raise StopIteration
    
    def get_cached_count(self) -> int:
        """获取已缓存的元素数量"""
        return len(self.cache)


class ChainIterator:
    """
    链式迭代器 - 连接多个可迭代对象
    
    类似于itertools.chain的实现
    """
    
    def __init__(self, *iterables):
        self.iterables = iterables
        self.current_iterable_index = 0
        self.current_iterator = None
    
    def __iter__(self):
        self.current_iterable_index = 0
        self.current_iterator = None
        return self
    
    def __next__(self):
        while self.current_iterable_index < len(self.iterables):
            # 初始化当前迭代器
            if self.current_iterator is None:
                self.current_iterator = iter(self.iterables[self.current_iterable_index])
            
            try:
                return next(self.current_iterator)
            except StopIteration:
                # 当前迭代器耗尽，移动到下一个
                self.current_iterable_index += 1
                self.current_iterator = None
        
        raise StopIteration


class ZipIterator:
    """
    压缩迭代器 - 并行迭代多个序列
    
    类似于内置zip函数的实现
    """
    
    def __init__(self, *iterables):
        self.iterators = [iter(iterable) for iterable in iterables]
    
    def __iter__(self):
        return self
    
    def __next__(self):
        try:
            return tuple(next(iterator) for iterator in self.iterators)
        except StopIteration:
            raise StopIteration


class EnumerateIterator:
    """
    枚举迭代器 - 添加索引信息
    
    类似于内置enumerate函数的实现
    """
    
    def __init__(self, iterable, start: int = 0):
        self.iterator = iter(iterable)
        self.index = start
    
    def __iter__(self):
        return self
    
    def __next__(self):
        try:
            value = next(self.iterator)
            result = (self.index, value)
            self.index += 1
            return result
        except StopIteration:
            raise StopIteration


# ============= 树形结构迭代器 =============

@dataclass
class TreeNode:
    """
    树节点
    
    用于演示树形结构的迭代
    """
    value: Any
    children: List['TreeNode'] = field(default_factory=list)
    parent: Optional['TreeNode'] = None
    
    def add_child(self, child: 'TreeNode'):
        """添加子节点"""
        child.parent = self
        self.children.append(child)
    
    def is_leaf(self) -> bool:
        """检查是否为叶子节点"""
        return len(self.children) == 0
    
    def is_root(self) -> bool:
        """检查是否为根节点"""
        return self.parent is None
    
    def get_depth(self) -> int:
        """获取节点深度"""
        depth = 0
        current = self.parent
        while current:
            depth += 1
            current = current.parent
        return depth


class TreeIterator:
    """
    树形结构迭代器基类
    
    提供不同的树遍历策略
    """
    
    def __init__(self, root: TreeNode):
        self.root = root
        self.stack = []
        self.visited = set()
    
    def __iter__(self):
        return self
    
    def __next__(self):
        raise NotImplementedError("子类必须实现__next__方法")


class PreOrderIterator(TreeIterator):
    """
    前序遍历迭代器
    
    根 -> 左子树 -> 右子树
    """
    
    def __init__(self, root: TreeNode):
        super().__init__(root)
        self.stack = [root] if root else []
    
    def __next__(self):
        if not self.stack:
            raise StopIteration
        
        node = self.stack.pop()
        
        # 将子节点逆序压入栈（这样先访问第一个子节点）
        for child in reversed(node.children):
            self.stack.append(child)
        
        return node


class PostOrderIterator(TreeIterator):
    """
    后序遍历迭代器
    
    左子树 -> 右子树 -> 根
    """
    
    def __init__(self, root: TreeNode):
        super().__init__(root)
        self.stack = []
        self.last_visited = None
        if root:
            self._push_left_path(root)
    
    def _push_left_path(self, node: TreeNode):
        """将从当前节点到最左叶子节点的路径压入栈"""
        while node:
            self.stack.append(node)
            node = node.children[0] if node.children else None
    
    def __next__(self):
        while self.stack:
            node = self.stack[-1]
            
            # 如果是叶子节点或所有子节点都已访问
            if not node.children or (self.last_visited and self.last_visited in node.children):
                self.stack.pop()
                self.last_visited = node
                return node
            
            # 找到下一个未访问的子节点
            next_child = None
            for child in node.children:
                if child != self.last_visited:
                    next_child = child
                    break
            
            if next_child:
                self._push_left_path(next_child)
        
        raise StopIteration


class LevelOrderIterator(TreeIterator):
    """
    层序遍历迭代器
    
    按层级从上到下、从左到右遍历
    """
    
    def __init__(self, root: TreeNode):
        super().__init__(root)
        self.queue = [root] if root else []
    
    def __next__(self):
        if not self.queue:
            raise StopIteration
        
        node = self.queue.pop(0)
        
        # 将子节点加入队列
        for child in node.children:
            self.queue.append(child)
        
        return node


class Tree:
    """
    树形结构容器
    
    支持多种遍历方式的树结构
    """
    
    def __init__(self, root: TreeNode = None):
        self.root = root
    
    def __iter__(self):
        """默认使用前序遍历"""
        return self.preorder_iter()
    
    def preorder_iter(self):
        """前序遍历"""
        return PreOrderIterator(self.root)
    
    def postorder_iter(self):
        """后序遍历"""
        return PostOrderIterator(self.root)
    
    def levelorder_iter(self):
        """层序遍历"""
        return LevelOrderIterator(self.root)
    
    def leaf_iter(self):
        """叶子节点迭代器"""
        for node in self.preorder_iter():
            if node.is_leaf():
                yield node
    
    def depth_iter(self, target_depth: int):
        """指定深度的节点迭代器"""
        for node in self.levelorder_iter():
            if node.get_depth() == target_depth:
                yield node


# ============= 异步迭代器 =============

class AsyncIterator:
    """
    异步迭代器 - Python 3.5+特性
    
    使用async/await语法实现异步迭代
    
    Python优势：
    - 原生支持异步迭代
    - 与asyncio完美集成
    - 适合I/O密集型操作
    """
    
    def __init__(self, data: List[Any], delay: float = 0.1):
        self.data = data
        self.delay = delay
        self.index = 0
    
    def __aiter__(self):
        """返回异步迭代器对象"""
        return self
    
    async def __anext__(self):
        """返回下一个元素（异步）"""
        if self.index >= len(self.data):
            raise StopAsyncIteration
        
        # 模拟异步操作（如网络请求、数据库查询等）
        await asyncio.sleep(self.delay)
        
        value = self.data[self.index]
        self.index += 1
        return value


async def async_generator(data: List[Any], delay: float = 0.1):
    """
    异步生成器函数
    
    使用async def和yield创建异步生成器
    """
    print("异步生成器开始执行")
    for i, item in enumerate(data):
        await asyncio.sleep(delay)  # 模拟异步操作
        print(f"异步生成第{i+1}个元素: {item}")
        yield item
    print("异步生成器执行完毕")


async def async_fibonacci(n: int, delay: float = 0.05):
    """
    异步斐波那契生成器
    
    演示异步无限序列生成
    """
    a, b = 0, 1
    count = 0
    
    while count < n:
        await asyncio.sleep(delay)
        yield a
        a, b = b, a + b
        count += 1


class AsyncFileReader:
    """
    异步文件读取器
    
    逐行异步读取文件内容
    """
    
    def __init__(self, file_path: str, chunk_size: int = 1024):
        self.file_path = file_path
        self.chunk_size = chunk_size
        self.file = None
    
    async def __aenter__(self):
        """异步上下文管理器入口"""
        # 在实际应用中，这里会使用aiofiles等异步文件库
        self.file = open(self.file_path, 'r', encoding='utf-8')
        return self
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        """异步上下文管理器出口"""
        if self.file:
            self.file.close()
    
    def __aiter__(self):
        return self
    
    async def __anext__(self):
        if not self.file:
            raise StopAsyncIteration
        
        # 模拟异步I/O操作
        await asyncio.sleep(0.01)
        
        line = self.file.readline()
        if not line:
            raise StopAsyncIteration
        
        return line.strip()


# ============= 实际应用示例 =============

class DataProcessor:
    """
    数据处理器 - 实际应用示例
    
    演示迭代器在数据处理中的应用
    """
    
    def __init__(self, data_source: Iterable[Any]):
        self.data_source = data_source
        self.processors = []
    
    def add_processor(self, processor_func):
        """添加处理函数"""
        self.processors.append(processor_func)
        return self  # 支持链式调用
    
    def process(self):
        """处理数据并返回生成器"""
        for item in self.data_source:
            processed_item = item
            
            # 依次应用所有处理器
            for processor in self.processors:
                processed_item = processor(processed_item)
            
            yield processed_item
    
    def batch_process(self, batch_size: int = 10):
        """批量处理数据"""
        batch = []
        for processed_item in self.process():
            batch.append(processed_item)
            
            if len(batch) >= batch_size:
                yield batch
                batch = []
        
        # 处理最后一批
        if batch:
            yield batch


class PaginatedIterator:
    """
    分页迭代器 - 模拟API分页数据获取
    
    演示实际业务场景中的迭代器应用
    """
    
    def __init__(self, total_items: int, page_size: int = 10, delay: float = 0.1):
        self.total_items = total_items
        self.page_size = page_size
        self.delay = delay
        self.current_page = 0
        self.current_item_index = 0
    
    def __iter__(self):
        self.current_page = 0
        self.current_item_index = 0
        return self
    
    def __next__(self):
        if self.current_item_index >= self.total_items:
            raise StopIteration
        
        # 模拟API调用延迟
        if self.current_item_index % self.page_size == 0:
            time.sleep(self.delay)
            self.current_page += 1
            print(f"获取第{self.current_page}页数据...")
        
        # 生成模拟数据
        item = {
            'id': self.current_item_index + 1,
            'name': f'Item_{self.current_item_index + 1}',
            'page': self.current_page,
            'timestamp': datetime.now().isoformat()
        }
        
        self.current_item_index += 1
        return item
    
    def get_page(self, page_num: int) -> List[Dict[str, Any]]:
        """获取指定页的数据"""
        start_index = (page_num - 1) * self.page_size
        end_index = min(start_index + self.page_size, self.total_items)
        
        if start_index >= self.total_items:
            return []
        
        time.sleep(self.delay)  # 模拟API延迟
        
        return [
            {
                'id': i + 1,
                'name': f'Item_{i + 1}',
                'page': page_num,
                'timestamp': datetime.now().isoformat()
            }
            for i in range(start_index, end_index)
        ]


class CacheIterator:
    """
    缓存迭代器 - 带缓存的迭代器
    
    演示性能优化的迭代器实现
    """
    
    def __init__(self, data_source: Iterable[Any], cache_size: int = 100):
        self.data_source = data_source
        self.cache_size = cache_size
        self.cache = []
        self.cache_index = 0
        self.source_iterator = None
        self.source_exhausted = False
    
    def __iter__(self):
        self.cache_index = 0
        if not self.source_iterator:
            self.source_iterator = iter(self.data_source)
        return self
    
    def __next__(self):
        # 如果缓存中有数据，直接返回
        if self.cache_index < len(self.cache):
            value = self.cache[self.cache_index]
            self.cache_index += 1
            return value
        
        # 如果数据源已耗尽
        if self.source_exhausted:
            raise StopIteration
        
        # 从数据源获取新数据
        try:
            value = next(self.source_iterator)
            
            # 添加到缓存（如果缓存未满）
            if len(self.cache) < self.cache_size:
                self.cache.append(value)
            
            self.cache_index += 1
            return value
        
        except StopIteration:
            self.source_exhausted = True
            raise
    
    def reset(self):
        """重置迭代器（使用缓存）"""
        self.cache_index = 0
    
    def get_cache_info(self) -> Dict[str, Any]:
        """获取缓存信息"""
        return {
            'cache_size': len(self.cache),
            'max_cache_size': self.cache_size,
            'current_index': self.cache_index,
            'source_exhausted': self.source_exhausted
        }


# ============= 演示函数 =============

def demonstrate_basic_iterators():
    """
    演示基础迭代器
    
    概述引导：
    展示Python迭代器协议的基本实现，包括__iter__和__next__方法。
    
    学习要点：
    1. 迭代器协议的实现
    2. StopIteration异常的使用
    3. 自定义迭代顺序
    4. 可迭代对象vs迭代器
    
    关键理解：
    Python的迭代器协议是for循环和其他迭代操作的基础。
    """
    print("=== 基础迭代器演示 ===")
    print("\n学习目标：")
    print("- 理解迭代器协议")
    print("- 掌握__iter__和__next__方法")
    print("- 学习StopIteration异常")
    print("\n重点概念：")
    print("- 迭代器协议")
    print("- 惰性求值")
    print("- 内存效率")
    print("=" * 50)
    
    # 基础迭代器测试
    print("\n=== 基础迭代器测试 ===")
    data = [1, 2, 3, 4, 5]
    iterator = BasicIterator(data)
    
    print("使用for循环:")
    for item in iterator:
        print(f"  {item}")
    
    print("\n手动迭代:")
    iterator.reset()
    try:
        while True:
            item = next(iterator)
            print(f"  手动获取: {item}")
    except StopIteration:
        print("  迭代完成")
    
    # 反向迭代器测试
    print("\n=== 反向迭代器测试 ===")
    reverse_iter = ReverseIterator(data)
    print("反向遍历:")
    for item in reverse_iter:
        print(f"  {item}")
    
    # 步长迭代器测试
    print("\n=== 步长迭代器测试 ===")
    step_iter = StepIterator(list(range(10)), step=2)
    print("步长为2的遍历:")
    for item in step_iter:
        print(f"  {item}")
    
    # 可迭代容器测试
    print("\n=== 可迭代容器测试 ===")
    container = IterableContainer([10, 20, 30, 40, 50])
    
    print("正向遍历:")
    for item in container:
        print(f"  {item}")
    
    print("\n反向遍历:")
    for item in container.reverse_iter():
        print(f"  {item}")
    
    print("\n步长遍历:")
    for item in container.step_iter(2):
        print(f"  {item}")
    
    # 多次迭代测试
    print("\n=== 多次迭代测试 ===")
    print("第一次遍历:")
    for item in container:
        print(f"  {item}")
    
    print("第二次遍历:")
    for item in container:
        print(f"  {item}")


def demonstrate_generators():
    """
    演示生成器函数
    """
    print("\n=== 生成器函数演示 ===")
    
    # 简单生成器测试
    print("\n简单生成器测试:")
    data = ['a', 'b', 'c', 'd']
    gen = simple_generator(data)
    
    print("生成器类型:", type(gen))
    print("遍历生成器:")
    for item in gen:
        print(f"  接收到: {item}")
    
    # 斐波那契生成器测试
    print("\n=== 斐波那契生成器测试 ===")
    fib_gen = fibonacci_generator(10)
    fib_numbers = list(fib_gen)
    print(f"前10个斐波那契数: {fib_numbers}")
    
    # 无限计数器测试
    print("\n=== 无限计数器测试 ===")
    counter = infinite_counter(start=100, step=5)
    print("前10个计数值:")
    for i, value in enumerate(counter):
        if i >= 10:
            break
        print(f"  {value}")
    
    # 过滤生成器测试
    print("\n=== 过滤生成器测试 ===")
    numbers = range(20)
    even_numbers = filtered_generator(numbers, lambda x: x % 2 == 0)
    print(f"偶数: {list(even_numbers)}")
    
    # 映射生成器测试
    print("\n=== 映射生成器测试 ===")
    words = ['hello', 'world', 'python', 'generator']
    uppercase_words = mapped_generator(words, str.upper)
    print(f"大写单词: {list(uppercase_words)}")
    
    # 批处理生成器测试
    print("\n=== 批处理生成器测试 ===")
    data = list(range(15))
    batches = batched_generator(data, batch_size=4)
    print("分批处理:")
    for i, batch in enumerate(batches):
        print(f"  批次{i+1}: {batch}")
    
    # 滑动窗口生成器测试
    print("\n=== 滑动窗口生成器测试 ===")
    data = list(range(8))
    windows = windowed_generator(data, window_size=3)
    print("滑动窗口:")
    for i, window in enumerate(windows):
        print(f"  窗口{i+1}: {window}")


def demonstrate_advanced_iterators():
    """
    演示高级迭代器
    """
    print("\n=== 高级迭代器演示 ===")
    
    # 惰性迭代器测试
    print("\n=== 惰性迭代器测试 ===")
    data = [1, 2, 3, 4, 5]
    lazy_iter = LazyIterator(data, lambda x: x ** 2)
    
    print("惰性计算平方值:")
    for item in lazy_iter:
        print(f"  {item}")
    
    print(f"缓存的元素数量: {lazy_iter.get_cached_count()}")
    
    # 链式迭代器测试
    print("\n=== 链式迭代器测试 ===")
    list1 = [1, 2, 3]
    list2 = ['a', 'b', 'c']
    list3 = [10, 20]
    
    chain_iter = ChainIterator(list1, list2, list3)
    print(f"链式迭代结果: {list(chain_iter)}")
    
    # 压缩迭代器测试
    print("\n=== 压缩迭代器测试 ===")
    names = ['Alice', 'Bob', 'Charlie']
    ages = [25, 30, 35]
    cities = ['New York', 'London', 'Tokyo']
    
    zip_iter = ZipIterator(names, ages, cities)
    print("压缩迭代结果:")
    for item in zip_iter:
        print(f"  {item}")
    
    # 枚举迭代器测试
    print("\n=== 枚举迭代器测试 ===")
    fruits = ['apple', 'banana', 'orange']
    enum_iter = EnumerateIterator(fruits, start=1)
    print("枚举结果:")
    for item in enum_iter:
        print(f"  {item}")


def demonstrate_tree_iterators():
    """
    演示树形结构迭代器
    """
    print("\n=== 树形结构迭代器演示 ===")
    
    # 构建测试树
    #       1
    #      /|\\n    #     2 3 4
    #    /|   |\\n    #   5 6   7 8
    #         |
    #         9
    
    root = TreeNode(1)
    node2 = TreeNode(2)
    node3 = TreeNode(3)
    node4 = TreeNode(4)
    node5 = TreeNode(5)
    node6 = TreeNode(6)
    node7 = TreeNode(7)
    node8 = TreeNode(8)
    node9 = TreeNode(9)
    
    root.add_child(node2)
    root.add_child(node3)
    root.add_child(node4)
    
    node2.add_child(node5)
    node2.add_child(node6)
    
    node4.add_child(node7)
    node4.add_child(node8)
    
    node7.add_child(node9)
    
    tree = Tree(root)
    
    # 前序遍历测试
    print("\n前序遍历 (根->左->右):")
    preorder_values = [node.value for node in tree.preorder_iter()]
    print(f"  {preorder_values}")
    
    # 后序遍历测试
    print("\n后序遍历 (左->右->根):")
    postorder_values = [node.value for node in tree.postorder_iter()]
    print(f"  {postorder_values}")
    
    # 层序遍历测试
    print("\n层序遍历 (按层级):")
    levelorder_values = [node.value for node in tree.levelorder_iter()]
    print(f"  {levelorder_values}")
    
    # 叶子节点遍历
    print("\n叶子节点:")
    leaf_values = [node.value for node in tree.leaf_iter()]
    print(f"  {leaf_values}")
    
    # 指定深度节点遍历
    print("\n深度为2的节点:")
    depth2_values = [node.value for node in tree.depth_iter(2)]
    print(f"  {depth2_values}")


async def demonstrate_async_iterators():
    """
    演示异步迭代器
    """
    print("\n=== 异步迭代器演示 ===")
    
    # 异步迭代器测试
    print("\n=== 异步迭代器测试 ===")
    data = ['async1', 'async2', 'async3']
    async_iter = AsyncIterator(data, delay=0.1)
    
    print("异步遍历:")
    async for item in async_iter:
        print(f"  异步接收: {item}")
    
    # 异步生成器测试
    print("\n=== 异步生成器测试 ===")
    async_gen = async_generator(['gen1', 'gen2', 'gen3'], delay=0.1)
    
    print("异步生成器遍历:")
    async for item in async_gen:
        print(f"  异步生成: {item}")
    
    # 异步斐波那契测试
    print("\n=== 异步斐波那契测试 ===")
    async_fib = async_fibonacci(8, delay=0.05)
    
    fib_values = []
    async for value in async_fib:
        fib_values.append(value)
    
    print(f"异步斐波那契数列: {fib_values}")


def demonstrate_practical_applications():
    """
    演示实际应用
    """
    print("\n=== 实际应用演示 ===")
    
    # 数据处理器测试
    print("\n=== 数据处理器测试 ===")
    raw_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    processor = DataProcessor(raw_data)
    processor.add_processor(lambda x: x * 2)  # 乘以2
    processor.add_processor(lambda x: x + 10)  # 加10
    processor.add_processor(lambda x: f"result_{x}")  # 格式化
    
    print("处理结果:")
    for item in processor.process():
        print(f"  {item}")
    
    print("\n批量处理结果:")
    for batch in processor.batch_process(batch_size=3):
        print(f"  批次: {batch}")
    
    # 分页迭代器测试
    print("\n=== 分页迭代器测试 ===")
    paginated = PaginatedIterator(total_items=25, page_size=5, delay=0.05)
    
    print("前10个项目:")
    for i, item in enumerate(paginated):
        if i >= 10:
            break
        print(f"  {item}")
    
    # 缓存迭代器测试
    print("\n=== 缓存迭代器测试 ===")
    
    def expensive_data_source():
        """模拟昂贵的数据源"""
        for i in range(5):
            print(f"    计算昂贵的值: {i}")
            time.sleep(0.1)  # 模拟计算时间
            yield i ** 3
    
    cache_iter = CacheIterator(expensive_data_source(), cache_size=10)
    
    print("第一次遍历（计算并缓存）:")
    first_pass = list(cache_iter)
    print(f"  结果: {first_pass}")
    print(f"  缓存信息: {cache_iter.get_cache_info()}")
    
    print("\n第二次遍历（使用缓存）:")
    cache_iter.reset()
    second_pass = list(cache_iter)
    print(f"  结果: {second_pass}")
    print(f"  缓存信息: {cache_iter.get_cache_info()}")


def demonstrate_performance_comparison():
    """
    演示性能对比
    """
    print("\n=== 性能对比演示 ===")
    
    # 列表 vs 生成器内存使用对比
    print("\n=== 内存使用对比 ===")
    
    def create_large_list(n):
        """创建大列表"""
        return [i ** 2 for i in range(n)]
    
    def create_large_generator(n):
        """创建大生成器"""
        return (i ** 2 for i in range(n))
    
    n = 100000
    
    # 列表方式
    start_time = time.time()
    large_list = create_large_list(n)
    list_creation_time = time.time() - start_time
    
    start_time = time.time()
    list_sum = sum(large_list)
    list_sum_time = time.time() - start_time
    
    # 生成器方式
    start_time = time.time()
    large_generator = create_large_generator(n)
    gen_creation_time = time.time() - start_time
    
    start_time = time.time()
    gen_sum = sum(large_generator)
    gen_sum_time = time.time() - start_time
    
    print(f"处理 {n} 个元素:")
    print(f"列表创建时间: {list_creation_time:.4f}秒")
    print(f"列表求和时间: {list_sum_time:.4f}秒")
    print(f"列表总时间: {list_creation_time + list_sum_time:.4f}秒")
    print(f"生成器创建时间: {gen_creation_time:.4f}秒")
    print(f"生成器求和时间: {gen_sum_time:.4f}秒")
    print(f"生成器总时间: {gen_creation_time + gen_sum_time:.4f}秒")
    print(f"结果验证: 列表={list_sum}, 生成器={gen_sum}")
    
    # 迭代器链式操作性能对比
    print("\n=== 链式操作性能对比 ===")
    
    data = list(range(10000))
    
    # 传统方式
    start_time = time.time()
    result1 = []
    for x in data:
        if x % 2 == 0:
            squared = x ** 2
            if squared > 100:
                result1.append(squared)
    traditional_time = time.time() - start_time
    
    # 生成器方式
    start_time = time.time()
    result2 = list(
        x ** 2 for x in data
        if x % 2 == 0 and x ** 2 > 100
    )
    generator_time = time.time() - start_time
    
    print(f"传统方式时间: {traditional_time:.4f}秒")
    print(f"生成器方式时间: {generator_time:.4f}秒")
    print(f"结果长度验证: 传统={len(result1)}, 生成器={len(result2)}")
    print(f"性能提升: {traditional_time/generator_time:.2f}x")


def demonstrate_java_comparison():
    """
    演示与Java的对比
    """
    print("\n=== Python vs Java 迭代器模式对比 ===")
    
    print("\n=== Java实现特点 ===")
    print("""
    Java迭代器模式的实现:
    
    // Java Iterator接口
    public interface Iterator<E> {
        boolean hasNext();
        E next();
        default void remove() {
            throw new UnsupportedOperationException("remove");
        }
    }
    
    // Java Iterable接口
    public interface Iterable<T> {
        Iterator<T> iterator();
    }
    
    // 具体实现
    public class MyIterator<T> implements Iterator<T> {
        private List<T> data;
        private int index = 0;
        
        public boolean hasNext() {
            return index < data.size();
        }
        
        public T next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            return data.get(index++);
        }
    }
    
    Java特点:
    - 使用hasNext()检查是否有下一个元素
    - 使用next()获取下一个元素
    - 需要显式的异常处理
    - 类型安全但代码冗长
    """)
    
    print("\n=== Python实现优势 ===")
    print("""
    Python迭代器模式的优势:
    
    1. 语法简洁:
       - 使用__iter__和__next__魔法方法
       - for循环自动处理StopIteration异常
       - 生成器函数提供更简洁的实现
    
    2. 生成器特性:
       - yield关键字创建生成器
       - 自动实现迭代器协议
       - 惰性求值，节省内存
    
    3. 内置支持:
       - 大量内置函数支持迭代器
       - 列表推导式和生成器表达式
       - 异步迭代器支持
    
    4. 灵活性:
       - 可以迭代任何实现了协议的对象
       - 支持无限序列
       - 易于组合和链式操作
    """)
    
    print("\n=== 使用场景对比 ===")
    print("""
    Java适用场景:
    - 大型企业应用
    - 需要严格类型检查
    - 集合框架的标准化迭代
    
    Python适用场景:
    - 数据处理和分析
    - 流式数据处理
    - 内存敏感的应用
    - 快速原型开发
    - 异步编程
    """)


def main():
    """
    主函数 - 演示所有迭代器模式实现
    """
    print("Python迭代器模式完整演示")
    print("=" * 60)
    
    # 基础迭代器演示
    demonstrate_basic_iterators()
    
    # 生成器演示
    demonstrate_generators()
    
    # 高级迭代器演示
    demonstrate_advanced_iterators()
    
    # 树形结构迭代器演示
    demonstrate_tree_iterators()
    
    # 异步迭代器演示
    print("\n开始异步演示...")
    asyncio.run(demonstrate_async_iterators())
    
    # 实际应用演示
    demonstrate_practical_applications()
    
    # 性能对比演示
    demonstrate_performance_comparison()
    
    # Java对比演示
    demonstrate_java_comparison()
    
    print("\n=== 总结 ===")
    print("""
    迭代器模式的Python实现要点:
    
    1. 基础协议：__iter__和__next__方法
    2. 生成器：使用yield的简洁实现
    3. 生成器表达式：内联的生成器创建
    4. 异步迭代器：支持async/await的异步迭代
    5. 内置支持：丰富的内置迭代器工具
    
    选择建议:
    - 简单迭代：使用生成器函数
    - 复杂逻辑：使用类实现迭代器协议
    - 内存敏感：使用生成器表达式
    - 异步场景：使用异步迭代器
    - 数据处理：结合内置函数和工具
    """)


if __name__ == "__main__":
    main()